using System;
using System.Collections.Generic;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;
using TenantManagementService.Monitoring;

namespace TenantManagementService.Monitoring
{
    /// <summary>
    /// 告警规则实体
    /// </summary>
    public class AlertRule : FullAuditedAggregateRoot<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 规则名称
        /// </summary>
        public virtual string Name { get; protected set; } = string.Empty;

        /// <summary>
        /// 规则显示名称
        /// </summary>
        public virtual string DisplayName { get; protected set; } = string.Empty;

        /// <summary>
        /// 规则描述
        /// </summary>
        public virtual string? Description { get; protected set; }

        /// <summary>
        /// 监控指标名称
        /// </summary>
        public virtual string MetricName { get; protected set; } = string.Empty;

        /// <summary>
        /// 告警级别
        /// </summary>
        public virtual AlertLevel Level { get; protected set; }

        /// <summary>
        /// 比较操作符（gt, lt, gte, lte, eq, ne）
        /// </summary>
        public virtual string Operator { get; protected set; } = "gt";

        /// <summary>
        /// 阈值
        /// </summary>
        public virtual decimal Threshold { get; protected set; }

        /// <summary>
        /// 持续时间（秒）
        /// </summary>
        public virtual int Duration { get; protected set; } = 60; // 默认60秒

        /// <summary>
        /// 评估间隔（秒）
        /// </summary>
        public virtual int EvaluationInterval { get; protected set; } = 30; // 默认30秒

        /// <summary>
        /// 是否启用
        /// </summary>
        public virtual bool IsEnabled { get; protected set; } = true;

        /// <summary>
        /// 标签过滤器（JSON格式）
        /// </summary>
        public virtual string? LabelFilters { get; protected set; }

        /// <summary>
        /// 通知渠道（JSON格式）
        /// </summary>
        public virtual string? NotificationChannels { get; protected set; }

        /// <summary>
        /// 规则表达式
        /// </summary>
        public virtual string? Expression { get; protected set; }

        /// <summary>
        /// 最后触发时间
        /// </summary>
        public virtual DateTime? LastTriggeredTime { get; protected set; }

        /// <summary>
        /// 触发次数
        /// </summary>
        public virtual int TriggerCount { get; protected set; } = 0;

        /// <summary>
        /// 关联的告警记录
        /// </summary>
        public virtual ICollection<Alert> Alerts { get; protected set; } = new List<Alert>();

        protected AlertRule() { }

        public AlertRule(
            Guid id,
            string name,
            string displayName,
            string metricName,
            AlertLevel level,
            string @operator,
            decimal threshold,
            string? description = null,
            int duration = 60,
            int evaluationInterval = 30,
            string? labelFilters = null,
            string? notificationChannels = null,
            string? expression = null,
            Guid? tenantId = null) : base(id)
        {
            Name = Check.NotNullOrWhiteSpace(name, nameof(name), maxLength: 200);
            DisplayName = Check.NotNullOrWhiteSpace(displayName, nameof(displayName), maxLength: 200);
            MetricName = Check.NotNullOrWhiteSpace(metricName, nameof(metricName), maxLength: 200);
            Level = level;
            Operator = Check.NotNullOrWhiteSpace(@operator, nameof(@operator), maxLength: 10);
            Threshold = threshold;
            Duration = duration > 0 ? duration : 60;
            EvaluationInterval = evaluationInterval > 0 ? evaluationInterval : 30;
            Description = description;
            LabelFilters = labelFilters;
            NotificationChannels = notificationChannels;
            Expression = expression;
            TenantId = tenantId;
            IsEnabled = true;
        }

        /// <summary>
        /// 更新基本信息
        /// </summary>
        public virtual AlertRule UpdateBasicInfo(
            string displayName,
            string? description = null,
            string? labelFilters = null,
            string? notificationChannels = null,
            string? expression = null)
        {
            DisplayName = Check.NotNullOrWhiteSpace(displayName, nameof(displayName), maxLength: 200);
            Description = description;
            LabelFilters = labelFilters;
            NotificationChannels = notificationChannels;
            Expression = expression;
            return this;
        }

        /// <summary>
        /// 更新阈值配置
        /// </summary>
        public virtual AlertRule UpdateThreshold(string @operator, decimal threshold, int duration = 60)
        {
            Operator = Check.NotNullOrWhiteSpace(@operator, nameof(@operator), maxLength: 10);
            Threshold = threshold;
            Duration = duration > 0 ? duration : 60;
            return this;
        }

        /// <summary>
        /// 更新评估配置
        /// </summary>
        public virtual AlertRule UpdateEvaluation(int evaluationInterval)
        {
            EvaluationInterval = evaluationInterval > 0 ? evaluationInterval : 30;
            return this;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        public virtual AlertRule UpdateStatus(bool isEnabled)
        {
            IsEnabled = isEnabled;
            return this;
        }

        /// <summary>
        /// 触发告警
        /// </summary>
        public virtual AlertRule TriggerAlert(decimal triggeredValue, Dictionary<string, string>? dimensions = null)
        {
            LastTriggeredTime = DateTime.Now;
            TriggerCount++;

            var alert = new Alert(
                Guid.NewGuid(),
                Id,
                Level,
                $"规则 '{DisplayName}' 被触发",
                $"指标 '{MetricName}' 的当前值 {triggeredValue} {Operator} {Threshold}",
                triggeredValue,
                dimensions,
                TenantId
            );

            Alerts.Add(alert);
            return this;
        }

        /// <summary>
        /// 检查规则是否匹配
        /// </summary>
        public virtual bool MatchesRule(decimal currentValue, Dictionary<string, string>? dimensions = null)
        {
            // 检查基本条件
            bool matchesThreshold = Operator.ToLower() switch
            {
                "gt" => currentValue > Threshold,
                "gte" => currentValue >= Threshold,
                "lt" => currentValue < Threshold,
                "lte" => currentValue <= Threshold,
                "eq" => currentValue == Threshold,
                "ne" => currentValue != Threshold,
                _ => false
            };

            if (!matchesThreshold)
            {
                return false;
            }

            // 检查标签过滤器
            if (!string.IsNullOrWhiteSpace(LabelFilters))
            {
                // 这里应该实现标签过滤逻辑
                // 简化实现，实际应该解析JSON并匹配
            }

            return true;
        }

        /// <summary>
        /// 获取标签过滤器
        /// </summary>
        public virtual Dictionary<string, string>? GetLabelFilters()
        {
            if (string.IsNullOrWhiteSpace(LabelFilters))
            {
                return null;
            }

            try
            {
                return System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, string>>(LabelFilters);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 获取通知渠道
        /// </summary>
        public virtual List<string>? GetNotificationChannels()
        {
            if (string.IsNullOrWhiteSpace(NotificationChannels))
            {
                return null;
            }

            try
            {
                return System.Text.Json.JsonSerializer.Deserialize<List<string>>(NotificationChannels);
            }
            catch
            {
                return null;
            }
        }
    }
}